package _05BigDecimal类;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class DemoBigDecimal {
    public static void main(String[] args) {
        //通过字符串创建
        BigDecimal b1 = new BigDecimal("0.1");
        //通过基本数据类型创建（容易丢失精度）
        BigDecimal b2 = new BigDecimal(0.1);

        System.out.println(b1);//0.1
        System.out.println(b2);//0.1000000000000000055511151231257827021181583404541015625
        System.out.println("===================================================");

        double d1 = 0.1;
        System.out.println(new BigDecimal(d1));//0.1000000000000000055511151231257827021181583404541015625
        System.out.println(new BigDecimal(d1+""));//0.1
        System.out.println("===================================================");

        BigDecimal decimal =new BigDecimal("0.2");
        //相加
        BigDecimal add = b1.add(decimal);
        System.out.println(add);//0.3
        System.out.println("===================================================");
        //相减
        BigDecimal subtract = b1.subtract(decimal);
        System.out.println(subtract);//-0.1
        System.out.println("===================================================");
        //相乘
        BigDecimal multiply = b1.multiply(decimal);
        System.out.println(multiply);//0.02
        System.out.println("===================================================");
        //相除（除得尽）
        BigDecimal divide = b1.divide(decimal);
        System.out.println(divide);//0.5
        System.out.println("===================================================");
        //相除（除不尽）
        BigDecimal divide2 = b1.divide(new BigDecimal("0.3"),2, RoundingMode.HALF_UP);//四舍五入，取小数点后两位
        System.out.println(divide2);//0.33
    }
}
